# -*- coding: utf-8 -*-
from mod_python import apache
from mod_python import util
import commands, os, shutil, base64, urllib, xmlrpclib

perlBeginString = "#!/usr/bin/perl\r\n"
pythonBeginString = "#!/usr/bin/python\r\n"

def writeData(req, data):
	req.set_content_length(len(data))
	req.write(data, 0)



def executeCode(req, fileName="_NOFILE", language="_NO_LANG"):

	result = "_NO_RESULT_OBTAINED"

	server_hostname = req.hostname
	server_url = 'http://' + server_hostname + ':8000/RPC2';
	server = xmlrpclib.Server(server_url)

	docRoot = req.document_root()
	totalFilePath = docRoot + fileName

	result = server.execCode(totalFilePath, language)

	writeData(req, result)
	return apache.OK

def getFileContents(req, fileName="_NOFILE"):
	req.content_type='text/data;charset=utf-8'
	docRoot = req.document_root()
	totalFilePath = docRoot + fileName

	try:
		fd = open(totalFilePath, 'r')
	except:
		writeData(req, "")
		return apache.OK
	
	data = fd.read()
	writeData(req, data)
	fd.close()
	return apache.OK

def createFile(req, filePath="_NOFILE"):

	docRoot = req.document_root()
	totalFilePath = docRoot + filePath
	try:
		fd = open(totalFilePath, 'w')
	except:
	   	writeData(req, "_FILE_CREATE_ERROR")
		return apache.OK

	try:
		fd.write("")
	except:
		writeData(req, "_FILE_WRITE_ERROR")
		return apache.OK
		
	try:
		fd.flush()
	except:
		writeData(req, "_FILE_FLUSH_ERROR")
		return apache.OK

	try:
		fd.close()
	except:
		writeData(req, "_FILE_CLOSE_ERROR")
		return apache.OK

	try:
		output = commands.getoutput("chmod 777 " + totalFilePath)
	except:
		writeData(req, "_FILE_CHMOD_ERROR")
		return apache.OK

	return apache.OK

def writeToFile(req, filePath="_NOFILE", fileContent="_NO_CONTENT"):

	origContent = base64.b64decode(fileContent)
	origContent = urllib.unquote(origContent)

	docRoot = req.document_root()
	totalFilePath = docRoot + filePath

	try:
		fd = open(totalFilePath, 'w')
	except:
		writeData(req, "_FILE_CREATE_ERROR")
		return apache.OK

	try:
		fd.write(origContent)
	except:
		writeData(req, "_FILE_WRITE_ERROR")
		return apache.OK

	try:
		fd.flush()
	except:
		writeData(req, "_FILE_FLUSH_ERROR")
		return apache.OK

	try:
		fd.close()
	except:
		writeData(req, "_FILE_CLOSE_ERROR")
		return apache.OK

	try:
		output = commands.getoutput("chmod 777 " + filePath)
	except:
		writeData(req, "_FILE_CHMOD_FAILED")
		return apache.OK


	return apache.OK

def deleteFile(req, filePath="_NOFILE"):

	filePath = urllib.unquote(filePath)
	docRoot = req.document_root()
	totalFilePath = docRoot + filePath

        try:
                os.remove(totalFilePath)
        except:
                writeData(req, "_OS_ERROR")
		return apache.OK
	
	return apache.OK
